﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.Data.Common;
using Microsoft.Practices.EnterpriseLibrary.Data;
using DuJianliang.ApplicationPlatform.Common;
using DuJianliang.ApplicationPlatform.UserPermission;

namespace DuJianliang.ApplicationPlatform.ExchangeAudit
{
    public partial class ExchangeAuditList_ZY : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!Page.IsPostBack)
            {
                BindGridView();
            }
        }

        private void BindGridView()
        {
//            string sql = @"SELECT A.*, C.FlowID, B.StepID, B.StepName, B.OperationName, B.OperationDate, B.OperatorInfo, B.Completed, B.CreateDate AS FlowCreateDate
//                            FROM dbo.t5715_ExchangeAudit A 
//                            LEFT JOIN dbo.FlowInstance B ON A.FlowInstanceID = B.FlowInstanceID
//                            LEFT JOIN dbo.FlowMain C ON C.TableName = 't5715_ExchangeAudit'
//                            ORDER BY CreateDate DESC";

//            Database database = DatabaseFactory.CreateDatabase();
//            DbCommand dbCommand = database.GetSqlStringCommand(sql);
//            DataTable dataTable = database.ExecuteDataSet(dbCommand).Tables[0];


            string sql = @"SELECT A.*, B.StepID, B.StepName, B.OperationName, B.OperationDate, B.OperatorInfo, B.Completed, B.CreateDate AS FlowCreateDate
                            ,
                            (
                              SELECT TOP 1 FSR.FlowID FROM dbo.FlowStepRelation FSR 
                              INNER JOIN dbo.FlowStepOperator FSO ON FSR.StepID = FSO.StepID
                              INNER JOIN dbo.FlowMain FM ON FSR.FlowID = FM.FlowID AND FM.TableName = 't5715_ExchangeAudit_ZY'
                              WHERE FSR.ParentID IS NULL AND FSO.OperatorInfo = @OperatorInfo
                            ) AS FlowID
                            FROM dbo.t5715_ExchangeAudit_ZY A 
                            LEFT JOIN dbo.FlowInstance B ON A.FlowInstanceID = B.FlowInstanceID {0} 
                            LEFT JOIN dbo.t5715_User C ON A.CreateUser = C.UserName
                            WHERE A.CreateUser = @OperatorInfo {1}
                            ORDER BY A.CreateDate DESC";

            string strWhere = string.Empty;
            switch (ddlFlowOperation.SelectedValue)
            {
                case "-1":
                    strWhere = string.Empty;
                    break;
                case "0":
                    strWhere = "WHERE B.OperationID IS NULL OR B.OperationID = ''";
                    break;
                case "1":
                    strWhere = "WHERE B.OperationID = 2 AND Completed = 1";
                    break;
                case "2":
                    strWhere = "WHERE B.OperationID = 4 AND Completed = 1";
                    break;
                case "3":
                    strWhere = "WHERE B.OperationID = 3";
                    break;
            }

            string childDeptWhere = string.Empty;
            string childDeptString = new UserPermissionBll().GetChildDeptIDString(CurrentInfo.Instance.CurrentUser.Dept.DeptID);
            if (!string.IsNullOrWhiteSpace(childDeptString))
            {
                childDeptWhere = string.Format("  OR C.DeptID IN ({0})", childDeptString);
            }

            sql = string.Format(sql, strWhere, childDeptWhere);

            Database database = DatabaseFactory.CreateDatabase();
            DbCommand dbCommand = database.GetSqlStringCommand(sql);
            database.AddInParameter(dbCommand, "@OperatorInfo", DbType.String, CurrentInfo.Instance.CurrentUser.UserName);
            DataTable dataTable = database.ExecuteDataSet(dbCommand).Tables[0];

            gridView.DataSource = dataTable;
            gridView.DataBind();
        }

        protected void btnCreate_Click(object sender, EventArgs e)
        {
            Response.Redirect("ExchangeAuditEdit_ZY.aspx?Source=list");
        }

        protected void gridView_RowCommand(object sender, GridViewCommandEventArgs e)
        {
            if (string.IsNullOrWhiteSpace(e.CommandName) || e.CommandName.ToLower().Equals("page"))
            {
                return;
            }

            GridViewRow gridViewRow = ((GridViewRow)(((Button)(e.CommandSource)).Parent.Parent));
            string flowInstanceID = gridView.DataKeys[gridViewRow.RowIndex]["FlowInstanceID"].ToString();

            switch (e.CommandName)
            {
                case "CmdEdit":
                    Response.Redirect(string.Format("ExchangeAuditEdit_ZY.aspx?flowInstanceID={0}&Source=list", flowInstanceID));
                    break;
                case "CmdShowFlow":
                    BindGridView();
                    break;
                case "CmdDelete":
                    Delete(flowInstanceID);
                    BindGridView();
                    break;
                default:
                    break;
            }
        }

        protected void gridView_RowDataBound(object sender, GridViewRowEventArgs e)
        {
            if (e.Row.RowType == DataControlRowType.DataRow)
            {
                string flowID = gridView.DataKeys[e.Row.RowIndex]["FlowID"].ToString();
                string flowInstanceID = gridView.DataKeys[e.Row.RowIndex]["FlowInstanceID"].ToString();

                TableCell tableCell_FlowCompleted = e.Row.Cells[3];
                string flowCompleted = tableCell_FlowCompleted.Text.ToLower();
                switch (flowCompleted)
                {
                    case "true":
                        tableCell_FlowCompleted.Text = "已完成";
                        e.Row.BackColor = System.Drawing.Color.LightGreen;
                        break;
                    case "false":
                        tableCell_FlowCompleted.Text = "处理中";
                        e.Row.BackColor = System.Drawing.Color.Pink;
                        break;
                    default:
                        tableCell_FlowCompleted.Text = "无";
                        break;
                }

                Button btnFlow = e.Row.Cells[5].FindControl("btnFlow") as Button;
                if (btnFlow != null)
                {
                    string url = string.Format("/Flow/FlowManager.aspx?FlowID={0}&FlowInstanceID={1}", flowID, flowInstanceID);
                    btnFlow.Attributes.Add("onclick", string.Format("showPage('{0}');", url));
                }

                Button btnDelete = e.Row.Cells[5].FindControl("btnDelete") as Button;
                if (btnDelete != null)
                {

                    if (!FlowHelper.HasFlowData(new Guid(flowInstanceID)))
                    {
                        btnDelete.Attributes.Add("onclick", "javascript:return confirm('确定要删除吗?')");
                    }
                    else
                    {
                        btnDelete.Visible = false;
                    }
                }
            }
        }

        private void Delete(string flowInstanceID)
        {
            string sql = @"DELETE FROM t5715_ExchangeAudit_ZY WHERE FlowInstanceID = @FlowInstanceID";

            Database database = DatabaseFactory.CreateDatabase();
            DbCommand dbCommand = database.GetSqlStringCommand(sql);
            database.AddInParameter(dbCommand, "@FlowInstanceID", DbType.String, flowInstanceID);
            database.ExecuteNonQuery(dbCommand);
        }

        protected void ddlFlowOperation_SelectedIndexChanged(object sender, EventArgs e)
        {
            BindGridView();
        }
    }
}